package org.springframework.amqp.tutorials.config;

import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitConfig {

    /**
     * 消息发送成功的回调
     */
    public RabbitTemplate.ConfirmCallback myconfirmCallback() {
        return new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("ConfirmCallback");
                System.out.println("相关数据：" + correlationData);
                System.out.println("确认情况：" + ack);
                System.out.println("原因：" + cause);
            }
        };
    }

    /**
     * 发生异常时的消息返回提醒
     */
    public RabbitTemplate.ReturnsCallback myReturnCallback() {
        return new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returned) {
                System.out.println("ReturnCallback");
                System.out.println("回应码：" + returned.getReplyCode());
                System.out.println("交换机：" + returned.getExchange());
                System.out.println("消息：" + returned.getMessage());
                System.out.println("路由键：" + returned.getRoutingKey());
                System.out.println("回应信息：" + returned.getReplyText());
            }
        };
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        // 消息发送成功的回调
//        rabbitTemplate.setMandatory(true);
        // 设置 confirmCallback
        rabbitTemplate.setConfirmCallback(myconfirmCallback());
        // 设置 returnCallback
        rabbitTemplate.setReturnsCallback(myReturnCallback());
        return rabbitTemplate;
    }

}